package org.lgiavedoni.android.franq.core.command;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import org.lgiavedoni.android.franq.core.message.MessageIn;
import org.lgiavedoni.android.franq.service.communication.CommunicationService;
import org.lgiavedoni.android.franq.service.log.Logger;
import org.lgiavedoni.android.franq.util.implementation.ImplementationUtil;

public class CommandManager {

	public static final CommandManager inst = new CommandManager();
	private final Map<String, Command> commands = new HashMap<String, Command>();
	private static final String IMPLEMENTATIONS_KEY = "commands";

	private CommandManager() {
		for (Object obj : ImplementationUtil.initialize(ImplementationUtil.getImplementations(IMPLEMENTATIONS_KEY))) {
			commands.put(((Command) obj).getCommandText().toLowerCase(), (Command) obj);
		}

	}

	public boolean tryToExecuteCommand(MessageIn message) {
		if (message.getText() == null)
			return false;
		String[] parts = message.getText().trim().toLowerCase().split(" ");
		if (commands.get(parts[0]) != null) {
			try {
				Command c = commands.get(parts[0]).getClass().newInstance();
				c.execute(parts);
			} catch (Exception ex) {
				Logger.inst.error(ex);
				CommunicationService.inst.sendDefaultTextMessage(commands.get(parts[0]).getHelpText());
			}
			return true;
		}

		return false;

	}

	public Set<String> getAllCommandKeys() {
		return commands.keySet();
	}
}
